/*
 * @Author: wangyongcun
 * @Date: 2023-09-22 17:32:02
 * @LastEditTime: 2024-05-12 11:41:33
 * @Description: 公共的方法类
 */

/**
 * @description: 请求类
 * @return {*}
 */
class ReqUtil {
  /**
   * @description: 请求非空校验
   * @param {*} keys 不允许为空的key值数组，不传默认reqBody的全部key
   * @param {*} ctx
   * @return {*}
   */
  isEmpty(keys = [], ctx) {
    try {
      let reqBody = ctx.request.body || {};
      for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (!reqBody[key]) {
          ctx.body = resUtil.error(`${key}参数不能为空！`);
          return true;
        }
      }
    } catch (err) {
      return `校验方法调用失败，失败原因：${err}`;
    }
  }
  /**
   * @description: 从对象里获取需要的参数对象
   * @param {*} params 参数对象
   * @param {*} keys 从中获取哪些key
   * @return {*}
   */
  getReqObj(reqBody = {}, keys = []) {
    let val = {};
    Object.keys(reqBody).forEach((key) => {
      if (keys.includes(key)) {
        val[key] = reqBody[key];
      }
    });
    return val;
  }
  /**
   * @description: 字符串：驼峰转下划线连字符
   * @param {*} str
   * @return {*}
   */
  camelToUnderline(str) {
    return str.replace(/([A-Z])/g, "_$1").toLowerCase();
  }
  /**
   * @description: 字符串：下划线转驼峰
   * @param {*} str
   * @return {*}
   */
  underlineToCamel(str) {
    return str.replace(/\_(\w)/g, (all, letter) => letter.toUpperCase());
  }
}
global.reqUtil = new ReqUtil();

/**
 * @description: 返回类
 * @return {*}
 */
class ResUtil {
  /**
   * @description: 成功返回
   * @param {*} res 入参
   * @return {*}
   */
  success(resBody) {
    return Object.assign(
      {
        Code: 200,
        Result: "success",
      },
      typeof resBody === "string"
        ? {
            Message: resBody,
          }
        : resBody
    );
  }
  /**
   * @description: 失败返回
   * @param {*} resBody
   * @return {*}
   */
  error(resBody) {
    return Object.assign(
      {
        Code: 500,
        Result: "error",
      },
      typeof resBody === "string"
        ? {
            Message: resBody,
          }
        : resBody
    );
  }
}

global.resUtil = new ResUtil();

/**
 * @description: uuid
 */
import { v4 as uuidv4 } from "uuid";
global.uuidv4 = uuidv4;

/**
 * @description: dayjs
 */
import dayjs from "dayjs";
global.dayjs = dayjs;
